package com.wm.eduService.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.wm.commonutils.result.ResultCode;
import com.wm.eduService.entity.EduCourse;
import com.wm.eduService.entity.EduCourseDescription;
import com.wm.eduService.entity.vo.*;
import com.wm.eduService.mapper.EduCourseMapper;
import com.wm.eduService.service.EduChapterService;
import com.wm.eduService.service.EduCourseDescriptionService;
import com.wm.eduService.service.EduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wm.eduService.service.EduVideoService;
import com.wm.servicebase.exceptionhandle.GuliException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author sshdg
 * @since 2020-10-01
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    EduCourseDescriptionService courseDescriptionService;
    @Autowired
    EduVideoService videoService;
    @Autowired
    EduChapterService chapterService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveCourseInfo(CourseInfoVo courseInfo) {
        //1.向课程表添加课程基本信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfo, eduCourse);
        boolean save1 = this.save(eduCourse);
        if (!save1){
            throw new GuliException(20001, "添加课程失败");
        }
        //2.向课程简介表添加简介
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfo.getDescription());
        courseDescription.setId(eduCourse.getId());
        boolean save = courseDescriptionService.save(courseDescription);
        if (!save){
            throw new GuliException(20001, "添加课程简介失败");
        }

        return eduCourse.getId();
    }

    @Override
    public CourseInfoVo getCourseInfoByCourseId(String courseId) {
        //1.查询课程信息
        EduCourse course = this.getById(courseId);
        CourseInfoVo courseInfoVo = new CourseInfoVo();

        BeanUtils.copyProperties(course,courseInfoVo);

        //2.查询课程描述信息
        EduCourseDescription courseDescription = courseDescriptionService.getById(courseId);
        courseInfoVo.setDescription(courseDescription.getDescription());
        return courseInfoVo;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCourse(CourseInfoVo courseInfo) {
        //1.修改课程信息
        EduCourse course = new EduCourse();
        BeanUtils.copyProperties(courseInfo,course);
        boolean updateResult = this.updateById(course);
        if(!updateResult){
            throw GuliException.from(ResultCode.UPDATE_ERROR);
        }

        //2.修改课程描述
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setId(courseInfo.getId());
        courseDescription.setDescription(courseInfo.getDescription());

        boolean updateDescResult = courseDescriptionService.updateById(courseDescription);

        if (!updateDescResult){
            throw GuliException.from(ResultCode.UPDATE_ERROR);
        }
    }

    /**
     * 根据课程id查询课程确认信息
     *
     * @param id 课程id
     * @return CoursePublishVo
     */
    @Override
    public CoursePublishVo publishCourseInfo(String id) {
        CoursePublishVo publishCourseInfo = this.baseMapper.getPublishCourseInfo(id);
        return publishCourseInfo;
    }

    /**
     * 查询课程基本信息
     *
     * @param courseId
     * @return
     */
    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return this.baseMapper.getBaseCourseInfo(courseId);
    }

    /**
     * 条件分页查询
     * @param page 分页对象（controller传过来的页码、页面大小）
     * @param courseQuery 前端传过来的查询对象
     * @return 包含查询完毕的total、数据等
     */
    @Override
    public Map<String, Object> pageQueryCourse(Page<EduCourse> page, CourseQuery courseQuery) {
        LambdaQueryWrapper<EduCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(courseQuery.getTitle()), EduCourse::getTitle, courseQuery.getTitle());
        queryWrapper.eq(!StringUtils.isEmpty(courseQuery.getSubjectParentId()), EduCourse::getSubjectParentId, courseQuery.getSubjectParentId());
        queryWrapper.eq(!StringUtils.isEmpty(courseQuery.getSubjectId()), EduCourse::getSubjectId, courseQuery.getSubjectId());
        queryWrapper.orderByDesc(EduCourse::getGmtCreate);
        this.page(page, queryWrapper);

        HashMap<String, Object> map = new HashMap<>();
        map.put("total", page.getTotal());
        map.put("records", page.getRecords());
        return map;
    }

    /**
     * 条件查询带分页查询课程
     *
     * @param coursePage  分页对象
     * @param courseQuery 条件查询
     * @return 查询结果
     */
    @Override
    public Map<String, Object> getCourseFrontList(Page<EduCourse> coursePage, CourseFrontQuery courseQuery) {
        LambdaQueryWrapper<EduCourse> courseWrapper = new LambdaQueryWrapper<>();
        //若一级分类不为空
        courseWrapper.eq(org.apache.commons.lang3.StringUtils.isNotBlank(courseQuery.getSubjectParentId()),EduCourse::getSubjectParentId,courseQuery.getSubjectParentId());
        //若二级分类不为空
        courseWrapper.eq(org.apache.commons.lang3.StringUtils.isNotBlank(courseQuery.getSubjectId()),EduCourse::getSubjectId,courseQuery.getSubjectId());

        //关注度不为空
        courseWrapper.orderByDesc(org.apache.commons.lang3.StringUtils.isNotBlank(courseQuery.getBuyCountSort()),EduCourse::getBuyCount);

        //最新不为空
        courseWrapper.orderByDesc(org.apache.commons.lang3.StringUtils.isNotBlank(courseQuery.getGmtCreateSort()),EduCourse::getGmtCreate);

        //价格不为空
        courseWrapper.orderByDesc(org.apache.commons.lang3.StringUtils.isNotBlank(courseQuery.getPriceSort()),EduCourse::getPrice);

        this.page(coursePage, courseWrapper);

        List<EduCourse> records = coursePage.getRecords();
        long current = coursePage.getCurrent();
        long pages = coursePage.getPages();
        long size = coursePage.getSize();
        long total = coursePage.getTotal();
        //下一页
        boolean hasNext = coursePage.hasNext();
        //上一页
        boolean hasPrevious = coursePage.hasPrevious();

        //把分页数据获取出来，放到map集合
        Map<String, Object> map = Maps.newHashMap();
        map.put("records", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCourse(String courseId) {
        //1.根据课程id删除小节
        videoService.deleteVideoByCourseId(courseId);

        //2.根据课程id删除章节
        chapterService.deleteChapterByCourseId(courseId);

        //3.根据课程id删除描述
        boolean removeDesc = courseDescriptionService.removeById(courseId);
        if(!removeDesc){
            throw GuliException.from(ResultCode.DELETE_ERROR);
        }

        //4.根据课程id删除课程本身
        boolean removeCourseResult = this.removeById(courseId);

        if(!removeCourseResult){
            throw GuliException.from(ResultCode.DELETE_ERROR);
        }
    }




}
